Popular Searches
Popular Course Categories
Popular Courses

Understanding Python Keywords and Identifiers

Understanding Python Keywords and Identifiers

Python Syntax, Variables, and Data Types

Understanding Python Keywords and Identifiers

Course: Python Training

Topic: Understanding Python Keywords and Identifiers

Course Link: Python Training Course at JustAcademy

Demo Link: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction to Python Keywords and Identifiers

Python is a high-level programming language with a readable syntax that helps developers write clear and maintainable programs. Two important elements of Python syntax are keywords and identifiers. Keywords are reserved words that have predefined meanings in the language, while identifiers are names given to variables, functions, classes, modules, and other program elements.

Understanding the difference between keywords and identifiers is essential when writing Python code. Keywords define the structure and behavior of a program, whereas identifiers help programmers refer to data and reusable program components.

For example, in total = 100, the name total is an identifier, the symbol = is an assignment operator, and 100 is an integer literal. In if total > 50:, the word if is a Python keyword and total remains an identifier.

Why Are Keywords and Identifiers Important?

  • They form the foundation of Python syntax.
  • They help define program logic and control flow.
  • They allow developers to name variables, functions, and classes.
  • They improve code readability and organization.
  • They help prevent syntax errors caused by invalid names or incorrect keyword usage.
  • They support consistent naming practices in larger projects.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Define Python keywords and identifiers.
  • Understand the difference between reserved words and user-defined names.
  • Recognize commonly used Python keywords.
  • Explain the rules for creating valid identifiers.
  • Understand case sensitivity in Python names.
  • Use Python's keyword module to inspect keywords.
  • Identify invalid identifiers and correct them.
  • Apply naming conventions to write readable Python programs.
  • Recognize common naming mistakes and troubleshoot related errors.

3. What Are Python Keywords?

Python keywords are reserved words that have special meanings in the Python language. They are part of Python's syntax and are used to define operations such as conditional execution, loops, function creation, exception handling, class definitions, and logical expressions.

Because keywords have predefined meanings, they generally cannot be used as ordinary identifiers. For example, assigning a value to a variable named if produces a syntax error.

Example of Python Keywords

if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible to vote")

In this example:

  • if is a keyword used for conditional execution.
  • else is a keyword that defines the alternative branch.
  • age is an identifier representing a variable.
  • print is the name of a built-in function, not a keyword.

4. Categories of Python Keywords

Python keywords serve different purposes. Grouping them by function makes it easier to understand where and why they are used.

Category Keywords Purpose
Conditional statements if, elif, else Make decisions based on conditions.
Loops for, while, break, continue Repeat instructions and control loop execution.
Function and class definitions def, return, class, lambda Define functions, classes, and anonymous functions.
Logical operations and, or, not Combine or reverse logical conditions.
Membership and identity in, is Check membership and object identity.
Exception handling try, except, finally, raise, assert Handle errors and validate assumptions.
Imports import, from, as Load modules and assign import aliases.
Scope and namespaces global, nonlocal, del Work with names and their scope.
Boolean and null values True, False, None Represent Boolean values and the absence of a value.
Context management with Manage resources such as files using a context manager.
Asynchronous programming async, await Define and work with asynchronous operations.
Pattern matching match, case Match values against patterns in supported Python versions.
Other language features pass, yield, yield from Provide placeholder statements and generator behavior.

Note: The exact keyword set depends on the Python version. Some words are soft keywords, which act as keywords only in particular syntactic contexts. The keyword module can be used to inspect the active interpreter's keyword information.

5. Common Python Keywords Explained

5.1 Conditional Keywords

The keywords if, elif, and else allow a program to select which instructions to execute.

marks = 78

if marks >= 90:
    print("Grade A")
elif marks >= 70:
    print("Grade B")
else:
    print("Needs improvement")

The program checks conditions in order. The first condition that evaluates to true determines the selected branch.

5.2 Loop Keywords

The for and while keywords repeat instructions. The break keyword exits a loop, while continue skips the remaining statements in the current iteration.

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

This example prints 1, 2, 4, and 5 because the iteration for 3 is skipped.

5.3 Function Keywords

The def keyword defines a function, and return sends a result back to the caller. The lambda keyword creates a small anonymous function.

def calculate_square(number):
    return number * number

result = calculate_square(5)
print(result)

Here, def and return are keywords, while calculate_square, number, and result are identifiers.

5.4 Logical Keywords

The keywords and, or, and not are used to combine or reverse logical conditions.

age = 25
has_id = True

if age >= 18 and has_id:
    print("Access permitted")

The condition is true only when both the age requirement and the identification requirement are satisfied.

5.5 Exception-Handling Keywords

Python uses try, except, else, and finally to manage exceptions. The raise keyword can explicitly raise an exception.

try:
    number = int("123")
except ValueError:
    print("Invalid number")
else:
    print("Conversion successful:", number)
finally:
    print("Operation completed")

The else block executes if the try block finishes without an exception. The finally block executes whether or not an exception occurs.

5.6 Import Keywords

The keywords import, from, and as help access code from modules and packages.

import math
from datetime import date as current_date

print(math.sqrt(81))
print(current_date.today())

In this example, math and current_date are identifiers. The words import, from, and as are keywords.

6. Hard Keywords and Soft Keywords

Python distinguishes between reserved keywords and soft keywords.

Hard Keywords

Hard keywords are reserved by the language grammar and cannot be used as ordinary identifiers. Examples include if, else, for, while, and def.

Soft Keywords

Soft keywords have special meanings in specific language constructs but can still be used as identifiers in other contexts. In modern Python versions, examples include match, case, and _ in particular contexts.

# "match" can be an ordinary identifier in this context.
match = "Python"

print(match)

This assignment is valid in Python versions where match is a soft keyword. Its role changes when it appears in a pattern-matching statement.

To avoid confusion, use the keyword module to check the active Python interpreter rather than relying on a list from a different version.

7. Checking Python Keywords Using the keyword Module

Python provides a built-in module called keyword. It allows developers to inspect the keyword list and test whether a particular string is a keyword.

Example 1: Display All Keywords

import keyword

print(keyword.kwlist)

The kwlist attribute returns a list of hard keywords for the current Python interpreter.

Example 2: Check Whether a Word Is a Keyword

import keyword

word = "while"

if keyword.iskeyword(word):
    print(word, "is a Python keyword")
else:
    print(word, "is not a hard keyword")

Output:

while is a Python keyword

Example 3: Check Soft Keywords

import keyword

word = "match"

print(keyword.issoftkeyword(word))

The result depends on the Python version and whether the given word is recognized as a soft keyword by that interpreter.

8. What Are Python Identifiers?

Identifiers are names assigned to program elements such as variables, functions, classes, modules, and objects. They allow programmers to store, access, organize, and reuse information.

Identifiers are created by the programmer, subject to Python's naming rules. Choosing meaningful names makes a program easier to read, debug, maintain, and collaborate on.

Example of Identifiers

student_name = "Aarav"
student_age = 21

def display_student():
    print(student_name, student_age)

display_student()

In this example:

  • student_name is a variable identifier.
  • student_age is a variable identifier.
  • display_student is a function identifier.

9. Rules for Creating Valid Python Identifiers

Python identifiers must follow specific rules. A name that breaks these rules can cause a syntax error.

Rule 1: An Identifier Must Begin With a Letter or Underscore

An identifier can begin with an uppercase letter, lowercase letter, or underscore. It cannot begin with a digit.

Identifier Valid? Explanation
name Yes Begins with a letter.
Student Yes Begins with an uppercase letter.
_count Yes Begins with an underscore.
2value No Begins with a digit.
9students No Begins with a digit.

Rule 2: Identifiers Can Contain Letters, Digits, and Underscores

After the first character, identifiers can contain letters, digits, and underscores. Spaces and most punctuation marks are not permitted in ordinary identifiers.

student1 = "Riya"
total_marks = 450
employee_code2026 = "EMP102"

The following names are invalid:

# Invalid identifiers:
# student name = "Riya"
# total-marks = 450
# employee@code = "EMP102"

Use underscores instead of spaces or hyphens when creating multiword names.

Rule 3: Identifiers Cannot Be Hard Keywords

Hard keywords are reserved by Python and cannot be used as ordinary identifiers.

# Invalid:
# class = "Python"

# Valid alternatives:
class_name = "Python"
course_class = "Beginner"

Using a reserved word as a variable name usually produces a syntax error.

Rule 4: Identifiers Are Case-Sensitive

Python treats uppercase and lowercase letters as different characters. As a result, identifiers that differ only by capitalization refer to different names.

score = 80
Score = 90
SCORE = 100

print(score)
print(Score)
print(SCORE)

Output:

80
90
100

Although these names are distinct, creating many identifiers that differ only by capitalization can make code difficult to understand. Prefer clear, consistent naming.

Rule 5: Identifiers Should Not Contain Spaces

Python does not permit spaces within ordinary identifiers. Use snake_case for variable and function names with multiple words.

# Incorrect:
# first name = "Neha"

# Correct:
first_name = "Neha"

Rule 6: Unicode Letters Are Supported

Python supports many Unicode characters in identifiers. However, for collaborative projects and widely used codebases, English letters, digits, and underscores are often preferred because they are familiar and easier to type across different keyboards.

café = "Coffee shop"
price = 150

print(café, price)

Unicode identifiers are legal in Python when they satisfy its identifier rules, but teams should follow consistent naming standards.

10. Valid and Invalid Identifier Examples

Identifier Status Reason
name Valid Starts with a letter.
first_name Valid Uses letters and an underscore.
marks2026 Valid Digits appear after the first character.
_temporary Valid Starts with an underscore.
studentName Valid Uses letters without spaces.
total_amount Valid Uses snake_case.
2marks Invalid Starts with a digit.
first-name Invalid as an identifier The hyphen is interpreted as a minus operator.
student name Invalid Contains a space.
for Invalid as an ordinary identifier It is a hard keyword.
name@value Invalid Contains an unsupported punctuation character.
total$value Invalid Contains a dollar sign.

11. Difference Between Keywords and Identifiers

Feature Keywords Identifiers
Meaning Reserved words with predefined language meanings. Names given to program elements.
Purpose Define syntax and language behavior. Refer to variables, functions, classes, and other objects.
Creation Defined by the Python language. Chosen by the programmer within naming rules.
Modification Cannot be redefined as ordinary identifiers when they are hard keywords. Can be named according to program requirements.
Case sensitivity Keyword spelling and capitalization matter. Identifiers are case-sensitive.
Examples if, else, for, def age, total, calculate_sum
Role in code Control how statements are interpreted. Identify the names used by the program.

Combined Example

def calculate_total(price, quantity):
    total = price * quantity
    return total

if calculate_total(100, 3) > 200:
    print("Purchase amount is high")

Keywords used: def, return, and if.

Identifiers used: calculate_total, price, quantity, and total.

12. Python Naming Conventions and Best Practices

Naming conventions are recommended practices that make Python code consistent and readable. They are not always enforced by the interpreter, but they are widely used in professional development.

Program Element Recommended Style Example
Variable snake_case student_age
Function snake_case calculate_average()
Class PascalCase StudentRecord
Constant UPPER_SNAKE_CASE MAX_RETRIES
Module Short lowercase name, often snake_case data_loader.py
Internal-use name Leading underscore by convention _internal_value

Best Practice 1: Choose Meaningful Names

Use identifiers that communicate the purpose of the value.

# Less descriptive
x = 500
y = 12

# More descriptive
monthly_salary = 50000
working_days = 22

Best Practice 2: Follow Consistent Naming Styles

Use snake_case for variables and functions, and PascalCase for classes. Consistency helps other developers understand your code quickly.

def calculate_discount(price, discount_rate):
    return price * discount_rate

class ShoppingCart:
    pass

Best Practice 3: Avoid Shadowing Built-in Names

Avoid assigning values to names of important built-in functions or types, such as list, str, sum, and id. Doing so can hide access to the original built-in within the relevant scope.

# Avoid:
# list = [1, 2, 3]

# Better:
numbers = [1, 2, 3]
print(list(numbers))

Using numbers instead of list allows the built-in list() function to remain available.

Best Practice 4: Avoid Ambiguous Names

Names such as l, O, and I can be confused with digits in some fonts. Prefer descriptive names such as item_count or order_total.

Best Practice 5: Use Constants Consistently

Python does not enforce constants through a dedicated constant keyword. By convention, names written in uppercase signal that a value should not be reassigned during normal program use.

TAX_RATE = 0.18
MAX_LOGIN_ATTEMPTS = 3

price = 1000
tax = price * TAX_RATE

print(tax)

Best Practice 6: Use Underscores Carefully

A leading underscore, such as _internal_value, conventionally signals that a name is intended for internal use. A double leading underscore inside a class can trigger name mangling. These naming patterns do not generally make a name completely private.

13. Using Identifiers in Variables, Functions, and Classes

13.1 Identifiers in Variables

Variables store references to objects and allow programs to work with values.

product_name = "Laptop"
product_price = 65000
is_available = True

print(product_name)
print(product_price)
print(is_available)

13.2 Identifiers in Functions

Function identifiers allow reusable operations to be called whenever needed.

def greet_user(user_name):
    message = f"Welcome, {user_name}!"
    return message

print(greet_user("Asha"))

13.3 Identifiers in Classes

Class identifiers define custom types that can group data and behavior.

class Employee:
    def __init__(self, employee_name, salary):
        self.employee_name = employee_name
        self.salary = salary

    def display_details(self):
        print(self.employee_name, self.salary)

employee = Employee("Karan", 45000)
employee.display_details()

Here, Employee is a class identifier, employee is a variable identifier, and display_details is a method identifier.

14. Checking Whether a Name Is a Valid Identifier

Python strings provide the isidentifier() method. It checks whether a string follows Python's identifier syntax. However, it does not by itself determine whether the name is a reserved hard keyword.

names = ["student_name", "2students", "first-name", "class"]

for name in names:
    print(name, name.isidentifier())

Expected output:

student_name True
2students False
first-name False
class True

The final result is True because class follows the general identifier character rules. However, class is a hard keyword and cannot be used as an ordinary variable name.

Combining isidentifier() With the keyword Module

import keyword

def is_valid_variable_name(name):
    return name.isidentifier() and not keyword.iskeyword(name)

test_names = ["student_name", "2students", "class", "total"]

for name in test_names:
    print(name, is_valid_variable_name(name))

This simple function checks both identifier syntax and hard-keyword status. In advanced scenarios, Python soft keywords and context-specific syntax may require additional consideration.

15. Common Errors Related to Keywords and Identifiers

Error Incorrect Example Correct Approach
Using a keyword as a variable if = 10 if_value = 10
Starting a name with a digit 3items = 30 items3 = 30
Using spaces in a name total price = 500 total_price = 500
Using a hyphen in a name first-name = "Ravi" first_name = "Ravi"
Accidental case mismatch print(Student) after defining student Use the exact identifier spelling consistently.
Shadowing a built-in sum = 10 total_sum = 10
Using an undefined identifier print(user_age) before defining it Define or correctly import the name before use.

Understanding SyntaxError

A SyntaxError occurs when Python cannot parse code according to its grammar. Using a hard keyword as a variable name or beginning an identifier with a digit are common examples.

# Incorrect:
# for = 5

# Correct:
loop_count = 5
print(loop_count)

Understanding NameError

A NameError occurs when Python tries to use a name that is not defined in the relevant scope.

student_name = "Maya"
print(student_name)

# This would raise NameError if no variable named student_age exists:
# print(student_age)

To fix a NameError, check spelling, capitalization, scope, and whether the variable or function was defined or imported correctly.

16. Practical Example: Student Marks Management

This example combines keywords and identifiers in a small program that calculates a student's average and determines a result.

def calculate_average(mark_one, mark_two, mark_three):
    total_marks = mark_one + mark_two + mark_three
    average_marks = total_marks / 3
    return average_marks

student_name = "Priya"
average = calculate_average(85, 90, 80)

if average >= 90:
    result = "Excellent"
elif average >= 75:
    result = "Very Good"
elif average >= 40:
    result = "Pass"
else:
    result = "Fail"

print("Student:", student_name)
print("Average:", round(average, 2))
print("Result:", result)

Explanation

  1. The def keyword defines the function.
  2. calculate_average is the function identifier.
  3. mark_one, mark_two, and mark_three are parameter identifiers.
  4. return sends the calculated average back to the caller.
  5. if, elif, and else control the result selection.
  6. student_name, average, and result are variable identifiers.
  7. print is a built-in function name, not a keyword.

17. Practical Example: Identifying Keywords and Identifiers

Consider the following code:

import keyword

def check_age(age):
    if age >= 18:
        return True
    else:
        return False

user_age = 20
print(check_age(user_age))
print(keyword.iskeyword("return"))
print(keyword.iskeyword("user_age"))

In this example:

  • import, def, if, return, and else are keywords.
  • keyword, check_age, age, and user_age are identifiers.
  • True and False are Boolean keywords in Python.
  • iskeyword() checks whether a supplied string is a hard keyword.

Expected output:

True
True
False

18. Troubleshooting Checklist

When a program produces errors related to names or keywords, use the following checklist:

  • Check whether the identifier begins with a letter or underscore.
  • Confirm that the name does not contain spaces or unsupported punctuation.
  • Verify that a hard keyword has not been used as an ordinary variable name.
  • Check uppercase and lowercase spelling carefully.
  • Confirm that the identifier has been defined before it is used.
  • Check whether a variable is accessible in the current scope.
  • Avoid overwriting built-in function and type names.
  • Use meaningful names and consistent naming conventions.
  • Check the Python version when working with soft keywords or newer syntax.
  • Read the complete error message and inspect the line indicated by the traceback.

19. Hands-On Exercises

Exercise 1: Identify the Keywords

Review the following code and identify every keyword.

def multiply(a, b):
    if a > 0 and b > 0:
        return a * b
    else:
        return 0

Expected answer: def, if, and, return, and else.

Exercise 2: Identify the Identifiers

Find the identifiers in the following code.

product_name = "Keyboard"
price = 1200

def display_product():
    print(product_name, price)

Expected answer: product_name, price, and display_product. The name print is also a referenced built-in function name, rather than a keyword.

Exercise 3: Correct the Invalid Names

Rewrite the following invalid assignments with valid identifiers.

# 1. 1student = "Amit"
# 2. first-name = "Amit"
# 3. class = "Python"
# 4. total marks = 450

Possible answers:

student1 = "Amit"
first_name = "Amit"
class_name = "Python"
total_marks = 450

Exercise 4: Create a Valid Identifier Checker

Write a Python program that accepts a string and reports whether it is a valid identifier and whether it is a hard keyword.

import keyword

name = input("Enter a name: ")

if not name.isidentifier():
    print("Invalid identifier syntax")
elif keyword.iskeyword(name):
    print("This is a reserved Python keyword")
else:
    print("Valid identifier name")

Exercise 5: Naming Convention Practice

Convert the following names to recommended Python styles:

  • Variable: StudentName → student_name
  • Function: CalculateTotal → calculate_total
  • Class: student_record → StudentRecord
  • Constant: maxAttempts → MAX_ATTEMPTS

20. Mini Project: Simple Employee Information Program

Objective: Build a small employee information program that demonstrates valid identifiers, meaningful naming conventions, and keywords used in functions and conditional statements.

Project Requirements

  • Store an employee's name, department, and monthly salary.
  • Create a function to calculate annual salary.
  • Use conditional statements to classify the salary.
  • Display the employee information in a readable format.
  • Use identifiers that follow Python naming conventions.

Sample Solution

def calculate_annual_salary(monthly_salary):
    return monthly_salary * 12

employee_name = "Ananya"
department_name = "Data Analytics"
monthly_salary = 45000

annual_salary = calculate_annual_salary(monthly_salary)

if annual_salary >= 600000:
    salary_category = "High annual salary"
else:
    salary_category = "Standard annual salary"

print("Employee Name:", employee_name)
print("Department:", department_name)
print("Monthly Salary:", monthly_salary)
print("Annual Salary:", annual_salary)
print("Category:", salary_category)

Skills Practiced

  • Using keywords to define functions and conditional logic.
  • Creating meaningful variable and function identifiers.
  • Following snake_case naming conventions.
  • Performing calculations and displaying results.
  • Reading and maintaining structured Python code.

21. Python Keywords and Identifiers: Interview Questions and Answers

Q1. What is a Python keyword?

Answer: A Python keyword is a reserved word with a predefined meaning in the language. Examples include if, for, def, and return.

Q2. What is an identifier in Python?

Answer: An identifier is a name assigned to a program element, such as a variable, function, class, or module.

Q3. Can a Python keyword be used as a variable name?

Answer: A hard keyword cannot be used as an ordinary identifier. For example, if = 10 causes a syntax error. Use a different name such as if_value.

Q4. What are the rules for naming identifiers?

Answer: An identifier must start with a letter or underscore, can contain letters, digits, and underscores, cannot contain spaces or unsupported punctuation, and cannot be a hard keyword.

Q5. Are Python identifiers case-sensitive?

Answer: Yes. Python treats name, Name, and NAME as different identifiers.

Q6. How can you find Python keywords programmatically?

Answer: Import the keyword module and use keyword.kwlist to retrieve the hard-keyword list for the current interpreter.

Q7. What is the purpose of the iskeyword() method?

Answer: The keyword.iskeyword() function checks whether a string is a hard keyword in the current Python interpreter.

Q8. What is the difference between isidentifier() and iskeyword()?

Answer: isidentifier() checks whether a string follows identifier syntax. iskeyword() checks whether the string is a hard keyword. A word such as class passes the identifier syntax check but is a hard keyword.

Q9. What is snake_case?

Answer: Snake_case is a naming style in which words are lowercase and separated by underscores, such as student_name and calculate_total. It is commonly recommended for variables and functions in Python.

Q10. What is PascalCase?

Answer: PascalCase capitalizes the first letter of each word without spaces or underscores. It is commonly used for class names, such as EmployeeRecord.

Q11. What is a soft keyword?

Answer: A soft keyword has a special meaning only in certain syntactic contexts. Its treatment depends on the language construct and Python version. The keyword.issoftkeyword() function can help identify soft keywords.

Q12. Why should built-in names be avoided as identifiers?

Answer: Reusing names such as list or sum can hide the corresponding built-in functions or types and cause unexpected behavior. More descriptive names help avoid this problem.

Q13. What is the difference between SyntaxError and NameError?

Answer: A SyntaxError means Python cannot parse the code correctly. A NameError occurs when code attempts to access a name that is not defined in the relevant scope.

Q14. Can an identifier contain numbers?

Answer: Yes, but it cannot start with a digit. For example, student2 is valid, while 2student is invalid.

Q15. Are naming conventions mandatory in Python?

Answer: Most naming conventions are recommendations rather than syntax requirements. Following conventions improves consistency, readability, and maintainability.

22. Quick Revision Notes

  • Keywords are reserved words with predefined language meanings.
  • Identifiers are names assigned to variables, functions, classes, and other program elements.
  • Hard keywords cannot be used as ordinary identifiers.
  • Identifiers begin with a letter or underscore.
  • Identifiers can contain letters, digits, and underscores.
  • Identifiers cannot contain spaces or unsupported punctuation.
  • Python identifiers are case-sensitive.
  • keyword.kwlist lists hard keywords for the current interpreter.
  • keyword.iskeyword() checks hard-keyword status.
  • keyword.issoftkeyword() checks soft-keyword status in supported Python versions.
  • str.isidentifier() checks identifier syntax.
  • Use snake_case for variables and functions.
  • Use PascalCase for classes.
  • Use uppercase names for constants by convention.
  • Avoid shadowing built-in names such as list and sum.
  • Use meaningful names to make code easier to understand and maintain.

23. Conclusion

Python keywords and identifiers are fundamental concepts that every Python learner should understand. Keywords provide the syntax needed to control program flow, define functions, handle exceptions, and perform other language operations. Identifiers allow developers to give meaningful names to variables, functions, classes, and other program elements.

By learning keyword categories, following identifier rules, understanding case sensitivity, and applying consistent naming conventions, programmers can reduce syntax errors and create readable, maintainable applications. Regular practice with small programs and identifier-checking exercises will strengthen these skills and prepare learners for more advanced Python topics.

24. Further Learning Resources

Continue learning Python through the following resources:

whatsapp